$(function(){

    var curEditMenuId = null;

    function MenuCreateModal(modalEle) {
        var self = this;
        self.$ele = modalEle;
        $('.save-btn',self.$ele).on('click',function(){
            self._onSave();
        });
        $('.cancel-btn',self.$ele).on('click',function() {
            self._onCancel();
        });
        self._initModal();
        self._initValidate();
    }

    MenuCreateModal.prototype = {
        constructor: MenuCreateModal,
        $ele: null,
        $permissionBox: null,
        $selectBox: null,
        $validater: null,
        tagBox: null,
        _initModal: function () {
            $(this.$ele).modal({
                backdrop: 'static',
                keyboard: false,
                show: false
            });
        },
        _initValidate: function() {
            this.validater = $('#menu-create-form').validate({
                rules: {},
                messages:
                    {},
                showErrors: function(errorMap, errorList){
                    if(errorList.length > 0) {
                        var error = errorList[0];
                        $(error.element).parent().addClass('has-error');
                        $('#menu-create-msg').show().find('p').text(error.message);
                    }
                },
                onkeyup: function(ele) {
                    $('#menu-create-msg').hide();
                    $(ele).parent().removeClass('has-error');
                },
                success: function(label,ele) {
                    console.log(lable);
                    console.log(ele);
                },
                submitHandler: function(){
                    $('#menu-create-box .overlay').show();
                    saveMenu();
                }

            });
        },
        getCheckedIdArr: function(){
            return this.tagBox.getCheckedTagIdArray();
        },
        _onCancel: function() {
            $(this.$ele).modal('hide');
        },
        _onSave: function() {
            $('form',this.$ele).submit();
        },
        _reset: function () {
            $('#menu-create-modal input:text').each(function(){
                $(this).val('');
            });
            $('#menu-create-msg').hide();
            $('.has-error').removeClass('has-error');
            $('#menu-create-box .overlay').hide();
        },
        close: function () {
            $(this.$ele).modal('hide');
        },
        open: function (menuInfo) {
            this._reset();
            if(menuInfo) {
                $('.menu-create-title',this.$ele).html('编辑菜单');
                for(var key in menuInfo) {
                    $('input[name="'+key+'"]',this.$ele).val(menuInfo[key]);
                }
            } else {
                $('.menu-create-title',this.$ele).html('新建菜单');
                $('#pid').val(1) ;
                $('#enable').val("1");
            }
            $(this.$ele).modal('show');
        }
    };

    var menuCreater = new MenuCreateModal($('#menu-create-modal'));

    /**
     * 增加按钮
     */
    $('#menu-create-btn').on('click',function(){
        curEditMenuId = null;
        menuCreater.open();
    });

    /**
     * 修改按钮
     */
    $('#menu-edit-btn').on('click',function(){

        var id = getEditCheckedId();
        if(id != 0){
            curEditMenuId = id;
            setEditModel(curEditMenuId)
        }

    });

    /**
     * 获取选中id
     */
    function getEditCheckedId(){

        var id = 0;
        //选中个数
        var size = $(".icheckbox_flat-blue.checked").length ;
        if(size == 0){
            alerting({
                msg: '请选择一条要修改的菜单项？',
                title: function(){
                    return '友情提示';
                }
            });
            return id ;
        }else if(size > 1){

            alerting({
                msg: '对不起，只能选择一条菜单项修改？',
                title: function(){
                    return '友情提示';
                }
            });
            return id ;
        }
        alert($(".icheckbox_flat-blue.checked").children('input').val());
        return  $(".icheckbox_flat-blue.checked").children('input').val() ;
    }

    /**
     * 刷新按钮
     */
    $('#menu-refresh-btn').on('click',function(){

        refresh();
    });
    function refresh(){
        window.location.reload();
    }

    /**
     * 编辑按钮
     */
    $('.edit-btn').on('click',function(){

        var $tr = $(this).parents('tr');
        curEditMenuId = $tr.attr('data-uid');
        setEditModel(curEditMenuId)
    });
    /**
     * 回填修改model值
     * @param curEditMenuIds
     */
    function setEditModel(curEditMenuId){

        cAjax({
            url: '/sysmenu/editModel',
            type: 'get',
            data: {
                id: curEditMenuId
            },
            success: function(obj) {
                console.log(obj);
                var menuInfo = obj.data;
                $("#pid").val(menuInfo.pid);
                $("#enable").val(menuInfo.enable);
                menuCreater.open(menuInfo);
            },
            error: function(obj) {
                console.log(obj);
            }
        });
    }

    /**
     * 增加or修改提交
     */
    function saveMenu() {
        var data = {},
            url = '';
        $('#menu-create-modal input:text').each(function(){
            var $this = $(this);
            data[$this.attr('name')] = $.trim($this.val());
        });
        $('#menu-create-modal select').each(function(){
            var $this = $(this);
            data[$this.attr('name')] = $.trim($this.val());
        });
        if(curEditMenuId == null) {
            url = '/sysmenu/insert';
        } else {
            data['id'] = curEditMenuId;
            url = '/sysmenu/edit';
        }
        console.log(data);
        menuCreater.close();

        cAjax({
            url: url,
            data: data,
            success: function(obj) {
                console.log(obj);
                greeting({
                    msg: obj.msg,
                    confirm: function(){
                        window.location.reload();
                    }

                });
            },
            error: function(obj){
                console.log(obj);
            }
        });
    }

    /**
     * 批量删除按钮
     *
     */
    var ids = '';
    $('#menu-delete-btn').on('click',function(){

        ids = getDeleteCheckedIds();
        if(ids != ''){
            deleteData(ids);
        }
    });
    /**
     * 获取选中id
     */
    function getDeleteCheckedIds(){
        ids = '';
        //选中个数
        var size = $(".icheckbox_flat-blue.checked").length ;
        if(size == 0){
            alerting({
                msg: '请选择要删除的菜单项？',
                title: function(){
                    return '友情提示';
                }
            });
            return ids ;
        }
        //拼接id值
        $(".icheckbox_flat-blue.checked").each(function(){
            var $this = $(this);
            ids += $this.children('input').val() +',';
        });
        return ids ;
    }


    /**
     * 单个删除操作
     */
    $('.menu-del-btn').on('click',function(){
        var $this = $(this);
        ids = $this.parents('tr').attr('data-uid')+',';
        deleteData(ids);
    });

    /**
     * 删除提交
     */
    function deleteData(ids){

        var msg = '确定要删除这条菜单吗？';
        var arry = ids.split(',');
        if(arry.length >1){msg = '确定要删除这些菜单吗？';}
        actionConfirm({
            msg: msg,
            confirm: function() {
                cAjax({
                    url:'/sysmenu/deleteByIds',
                    type:'post',
                    data:{ids:ids },
                    success:function(obj){
                        console.log(obj);
                        greeting({
                            msg: obj.msg,
                            confirm: function(){
                                window.location.reload();
                            }
                        });
                        // $this.parents('tr').addClass('deleted');
                        // $this.parent().html('<span class="label label-warning">已删除</span>');
                    },
                    error: function(obj) {
                        console.log(obj);
                        greeting({
                            msg: obj.msg
                        })
                    }
                });
            }
        });
    }
});
